﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using EyFramework.Sys.Entity;
using EyFramework.Task.Entity;
using Newtonsoft.Json;

namespace EyFramework.Task.Excutor
{
    /// <summary>
    /// C#函数反射方式直接调用DLL
    /// </summary>
    public class CSharpJobExecutor : IJobExecutor
    {
        public ReturnData Execute(QrtzCsTask pTaskInfo)
        {
            ReturnData rd = new ReturnData();
            try
            {  //加载程序集(dll文件地址)，使用Assembly类
                SharpFileInfo sfi = JsonConvert.DeserializeObject<SharpFileInfo>(pTaskInfo.TASK_INFO);
                if (sfi.SINGLE_PROCESS == "Y")
                {
                    //现将参数写入临时文件，
                    string fileName = CreateTransFile(pTaskInfo);
                    Process proc = Process.Start("ScAutoRun.exe", fileName);
                    proc.WaitForExit();
                }
                else
                {
                    RunCsharp(sfi, rd);
                }
            }
            catch (Exception ex)
            {
                return rd.Fail(ex.ToString());
            }
            return rd;
        }

        private string CreateTransFile(QrtzCsTask pTaskInfo)
        {
            string content = JsonConvert.SerializeObject(pTaskInfo);
            string sFileName = pTaskInfo.TASK_NAME + "-" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
            string sFile = System.AppDomain.CurrentDomain.BaseDirectory + "\\" + sFileName;
            if (File.Exists(sFile))
            {
                File.Delete(sFile);
            }
            FileStream fs = File.Create(sFile);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(content);
            sw.Close();
            fs.Close();
            return sFileName;
        }

        private void RunCsharp(SharpFileInfo sfi, ReturnData rd)
        {
            Assembly assembly = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + sfi.FILE_NAME);

            //获取类型，参数（名称空间+类）
            Type type = assembly.GetType(sfi.CLASS_NAME);

            //创建该对象的实例，object类型，参数（名称空间+类）
            object instance = assembly.CreateInstance(sfi.CLASS_NAME);

            //设置方法的参数类型，Type[]类型；如有多个参数可以追加多个
            Type[] parmsType = new Type[1];
            parmsType[0] = Type.GetType("System.String");

            MethodInfo method = type.GetMethod(sfi.METHOD_NAME);

            //执行方法
            object value = method.Invoke(instance, null);
            if (null != value && !string.IsNullOrEmpty(value.ToString()))
            {
                rd.Success = false;
                rd.Message = value.ToString();
            }
        }
    }
}